<template>
  <div class="bg-fa of">
    <!-- 公共头 -->
    <AppHeader :inputName="user.name"/>
    <!-- /公共头 -->

    <section id="index" class="container">
      <header class="comm-title">
        <h2 class="fl tac">
          <span class="c-333">课程列表</span>
        </h2>
      </header>
      <ul>
        <li v-for="product in productList" :key="product.id">
          <a :class="['orderBtn', {current:payOrder.productId === product.id}]"
             @click="selectItem(product.id)"
             href="javascript:void(0);">
            {{ product.title }}
            ¥{{ product.price / 100 }}
          </a>
        </li>
      </ul>

      <div class="PaymentChannel_payment-channel-panel">
        <h3 class="PaymentChannel_title">
          选择支付方式
        </h3>
        <div class="PaymentChannel_channel-options">
          <!-- 选择微信 -->
          <div :class="['ChannelOption_payment-channel-option', {current:payOrder.payType === 'wxpay'}]"
               @click="selectPayType('wxpay')">
            <div class="ChannelOption_channel-icon">
              <img src="../assets/img/wxpay.png" class="ChannelOption_icon">
            </div>
            <div class="ChannelOption_channel-info">
              <div class="ChannelOption_channel-label">
                <div class="ChannelOption_label">微信支付</div>
                <div class="ChannelOption_sub-label"></div>
                <div class="ChannelOption_check-option"></div>
              </div>
            </div>
          </div>

        </div>
      </div>

      <div class="payButtom">
        <el-button
            :disabled="payBtnDisabled"
            type="warning"
            round
            style="width: 180px;height: 44px;font-size: 18px;"
            @click="toPay()">
          确认支付
        </el-button>
      </div>
    </section>

    <!-- 微信支付二维码 -->
    <el-dialog
        :visible.sync="codeDialogVisible"
        :show-close="false"
        @close="closeDialog"
        width="350px"
        center>
      <qriously :value="codeUrl" :size="300"/>
      使用微信扫码支付
    </el-dialog>

    <!-- 公共底 -->
    <AppFooter/>
    <!-- /公共底 -->
  </div>
</template>

<script>
import productApi from '../api/product'
import wxPayApi from '../api/wxPay'
import orderInfoApi from '../api/orderInfo'
import AppHeader from '../components/AppHeader'
import selectUserByName from "../api/login"
import AppFooter from '../components/AppFooter'
import '../assets/css/reset.css'
import '../assets/css/theme.css'
import '../assets/css/global.css'

export default {
  components: {
    AppHeader, AppFooter
  },
  data() {
    return {
      payBtnDisabled: false, //确认支付按钮是否禁用
      codeDialogVisible: false, //微信支付二维码弹窗
      productList: [], //商品列表
      payOrder: { //订单信息
        productId: '', //商品id
        payType: 'wxpay' //支付方式
      },
      codeUrl: '', // 二维码
      orderNo: '', //订单号
      timer: null, // 定时器
      // 存储兄弟组件login传过来的user信息
      user: {
        id: null,
        name: "未登录"
      }
    }
  },
  mounted() {
    // 获取兄弟组件传的值
    this.$bus.$on("name", name => {
        this.user.name = name;
        // 根据name查询user信息
        selectUserByName.selectUserByName(this.user.name).then(r => {
          this.user.id = r.data.user.id
          // 将整个user对象存入浏览器缓存
          localStorage.setItem("user", JSON.stringify(this.user))
        })
    })
  },
  created() {
    //获取商品列表
    productApi.list().then(response => {
      this.productList = response.data.productList
      this.payOrder.productId = this.productList[0].id
    })
    // 20毫秒后读取浏览器缓存
    if(JSON.parse(localStorage.getItem('user')).id !== null){
      setTimeout(() => {
        this.user = JSON.parse(localStorage.getItem('user'))
      }, 20)
    }
  },
  methods: {
    //选择商品
    selectItem(productId) {
      this.payOrder.productId = productId
    },
    //选择支付方式
    selectPayType(type) {
      this.payOrder.payType = type
    },
    //确认支付
    toPay() {
      if (this.user.id === null) {
        this.$router.push("/login")
      } else {
        //禁用按钮，防止重复提交
        this.payBtnDisabled = true
        //微信支付
        if (this.payOrder.payType === 'wxpay') {
          //调用统一下单接口
          wxPayApi.nativePay(this.payOrder.productId, this.user.id).then(response => {
            this.codeUrl = response.data.codeUrl
            this.orderNo = response.data.orderNo
            //打开二维码弹窗
            this.codeDialogVisible = true
            //启动定时器
            this.timer = setInterval(() => {
              //查询订单是否支付成功
              this.queryOrderStatus()
            }, 3000)
          })
        }
      }
    },
    //关闭微信支付二维码对话框时让“确认支付”按钮可用
    closeDialog() {
      this.payBtnDisabled = false
      clearInterval(this.timer)  // 清除定时器
    },
    // 查询订单状态
    queryOrderStatus() {
      orderInfoApi.queryOrderStatus(this.orderNo).then(response => {
        if (response.code === 0) {
          clearInterval(this.timer)  // 清除定时器
          // 5毫秒后提示支付成功
          setTimeout(() => {
            this.payBtnDisabled = false
            this.codeDialogVisible = false
            this.$message.success("支付成功！")
          }, 5)
        }
      })
    }
  }
}
</script>
